import logging

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

import user
from comm.util import utils
from user.models import User

# Create your views here.

logger = logging.getLogger(__name__)


# 用户注册
def register(request):
    """
    用户注册
    :param request:
    :return:
    """
    logger.info('进入用户注册')
    error_msg = {}
    if request.method == 'GET':
        return render(request, 'user/register.html')
    if request.method == "POST":
        email = request.POST.get('email', '')
        password = request.POST.get('password', '')
        name = request.POST.get('name', '')

        # 校验输入数据合法性
        if email.lstrip() == '':
            error_msg["email"] = '邮件地址不能为空'
        elif not utils.valid_email(email):
            error_msg["email"] = '邮件地址格式不正确'

        if name.lstrip() == '':
            error_msg["name"] = '昵称不能为空'

        if password.lstrip() == '':
            error_msg["password"] = '密码不能为空'
        elif len(password.lstrip()) < 8:
            error_msg["password"] = '密码不能小于8位长度'

        # 判断若错误信息 则返回注册页面
        if error_msg:
            return render(request, 'user/register.html', locals())

        # 判断用户是否已注册
        try:
            u = User.objects.get(email=email)
            logger.info("用户是否被注册[%s]", user)
            if u:
                error_msg["user_exist"] = '邮件地址被注册'
            return render(request, 'user/register.html', locals())
        except user.models.User.DoesNotExist:
            # 用户保存数据库
            u = User.objects.create(uid=utils.get_uuid(), name=name, email=email, password=password)
            u.save()
            # 重置数据
            password = ''

            # 保持会话
            request.session['user_uid'] = u.uid
            request.session['user_name'] = u.name
            request.session['is_login'] = True
            # logger.info("清理[Session]缓存")
            # request.session.flush()
            # 退出浏览器自动关闭
            request.session.set_expiry(0)
            return HttpResponseRedirect("/")


@csrf_exempt
def login(request):
    """
    用户登陆
    :param request:
    :return:
    """
    logger.info("进入用户登陆")
    error_msg = {}
    if request.method == 'GET':
        return render(request, 'user/login.html')
    if request.method == "POST":
        email = request.POST.get('email', '')
        password = request.POST.get('password', '')
        valid_code = request.POST.get('valid_code', '')
        logger.info("valid_code=[%s],email=[%s],password=[%s]", valid_code,email, password)
        # 校验输入数据合法性
        if valid_code != "success":
            error_msg["valid_code"] = '滑动验证不通过'
        if email.lstrip() == '':
            error_msg["email"] = '邮件地址不能为空'
        if password.lstrip() == '':
            error_msg["password"] = '密码不能为空'

        # 判断若错误信息 则返回注册页面
        if error_msg:
            return render(request, 'user/login.html', locals())

        # 判断用户是否已注册
        try:
            u = User.objects.get(email=email, password=password)
            logger.info("[%s]登陆成功", u.name)
            # 保持会话
            request.session['user_uid'] = u.uid
            request.session['user_name'] = u.name
            request.session['is_login'] = True
            # 退出浏览器自动关闭
            request.session.set_expiry(0)
            # logger.info("清理[Session]缓存")
            # request.session.flush()
            # 跳转到首页
            return HttpResponseRedirect("index")
        except user.models.User.DoesNotExist:
            error_msg["login"] = '账号或密码不正确'
            logger.info(error_msg)
            return render(request, 'user/login.html', locals())


# GEETEST 活动认证

def logout(request):
    """
    退出
    :param request:
    :return:
    """
    try:
        del request.session['user_uid']
        del request.session['user_name']
        del request.session['is_login']
    finally:
        logger.info("退出登陆，删除[session]数据")
    # 退出浏览器自动关闭
    request.session.set_expiry(0)
    return HttpResponseRedirect("index")
